// FormControlHandler.cs
//

namespace ServiceAdmin
{
    using System;
	using System.Collections;
    using System.Windows.Forms;


    /// <summary>
    /// Summary description for FormControlHandler.
    /// </summary>
    public class FormControlHandler
    {
		private Form		_form			= null;
		private ArrayList	_controlNames	= new ArrayList();


		/// <summary>
		///
		/// </summary>
		public bool IsFixedSize
		{
			get { return false; }
		}


		public bool IsReadOnly
		{
			get { return false; }
		}


    	public FormControlHandler(Form form)
    	{
			_form = form;
			_form.Disposed += new EventHandler(Dispose);
    	}


		public Control this[int index]
		{
			get { return _form.Controls[index]; }
		}


		public Control this[string name]
		{
			get { return this[FindValidControl(name)]; }
		}


		public int Add(Control value, string name)
		{
			_form.Controls.Add(value);
			return _controlNames.Add(name);
		}


		public void Clear()
		{
			_form.Controls.Clear();
		}


		public bool Contains(Control value)
		{
			return _form.Controls.Contains(value);
		}


		public bool Contains(string controlName)
		{
			return _controlNames.Contains(controlName);
		}


		public int IndexOf(Control value)
		{
			return _form.Controls.IndexOf(value);
		}


		public int IndexOf(string value)
		{
			return _controlNames.IndexOf(value);
		}


		public void Remove(Control value)
		{
			_form.Controls.Remove(value);
			_controlNames.Remove(value.Name);
		}


		public void Remove(string controlName)
		{
			RemoveAt(FindValidControl(controlName));
		}


		public void RemoveAt(int index)
		{
			_form.Controls.RemoveAt(index);
			_controlNames.RemoveAt(index);
		}


		public Control FindControl(string name)
		{
			if (name != null)
			{
				int controlIndex = FindControlByName(name);

				if (controlIndex != -1)
				{
					return _form.Controls[controlIndex];
				}
			}
			return null;
		}


		private int FindValidControl(string name)
		{
			int controlIndex = FindControlByName(name);

			if (controlIndex == -1)
			{
				throw new ArgumentException("Could not find a control with the given name.");
			}
			return controlIndex;
		}


		private int FindControlByName(string name)
		{
			return _controlNames.IndexOf(name);
		}


		private void Dispose(object sender, EventArgs e)
		{
			for (int i = 0; i < _form.Controls.Count; ++i)
			{
				_form.Controls[i].Dispose();
			}
		}
  	}
}